import React, { useState, useEffect } from 'react';

const SearchBar = ({ 
  onSearch, 
  searchResults = [], 
  currentIndex = -1, 
  onNext, 
  onPrevious 
}) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [isVisible, setIsVisible] = useState(false);

  // 处理搜索输入
  const handleSearchChange = (e) => {
    const value = e.target.value;
    setSearchTerm(value);
    if (onSearch) {
      onSearch(value);
    }
  };

  // 处理输入事件（包括粘贴）
  const handleInput = (e) => {
    const value = e.target.value;
    setSearchTerm(value);
    if (onSearch) {
      onSearch(value);
    }
  };

  // 处理粘贴事件
  const handlePaste = (e) => {
    // 允许默认粘贴行为，然后在input事件中处理
    // 这样可以确保在所有环境中都能正常工作
  };

  // 处理键盘快捷键
  useEffect(() => {
    const handleKeyDown = (e) => {
      // Ctrl+F 或 Cmd+F 打开搜索
      if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
        e.preventDefault();
        setIsVisible(true);
        // 聚焦搜索框
        setTimeout(() => {
          const searchInput = document.querySelector('.search-input');
          if (searchInput) {
            searchInput.focus();
          }
        }, 100);
      }
      
      // ESC 关闭搜索
      if (e.key === 'Escape') {
        setIsVisible(false);
        setSearchTerm('');
        if (onSearch) {
          onSearch('');
        }
      }
      
      // Enter 下一个结果
      if (e.key === 'Enter' && isVisible && searchResults.length > 0) {
        e.preventDefault();
        if (e.shiftKey) {
          onPrevious && onPrevious();
        } else {
          onNext && onNext();
        }
      }
      
      // Ctrl+V 粘贴支持（确保焦点在搜索框）
      if ((e.ctrlKey || e.metaKey) && e.key === 'v' && isVisible) {
        const searchInput = document.querySelector('.search-input');
        if (searchInput && document.activeElement !== searchInput) {
          searchInput.focus();
        }
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [isVisible, searchResults.length, onNext, onPrevious, onSearch]);

  // 清除搜索
  const clearSearch = () => {
    setSearchTerm('');
    if (onSearch) {
      onSearch('');
    }
  };

  if (!isVisible) {
    return (
      <div className="search-toggle">
        <button 
          className="btn btn-sm btn-outline-secondary"
          onClick={() => setIsVisible(true)}
          title="搜索 (Ctrl+F)"
        >
          <i className="fas fa-search"></i> 搜索
        </button>
      </div>
    );
  }

  return (
    <div className="search-bar-container">
      <div className="search-bar">
        <div className="input-group input-group-sm">
          <input
            type="text"
            className="form-control search-input"
            placeholder="搜索日志内容..."
            value={searchTerm}
            onChange={handleSearchChange}
            onInput={handleInput}
            onPaste={handlePaste}
            autoFocus
          />
          
          {searchTerm && (
            <button 
              className="btn btn-outline-secondary"
              type="button"
              onClick={clearSearch}
              title="清除搜索"
            >
              <i className="fas fa-times"></i>
            </button>
          )}
          
          <button 
            className="btn btn-outline-secondary"
            type="button"
            onClick={() => setIsVisible(false)}
            title="关闭搜索 (ESC)"
          >
            <i className="fas fa-times"></i>
          </button>
        </div>
        
        {searchResults.length > 0 && (
          <div className="search-results-info">
            <span className="search-count">
              {currentIndex + 1} / {searchResults.length}
            </span>
            
            <div className="search-navigation">
              <button 
                className="btn btn-sm btn-outline-secondary"
                onClick={onPrevious}
                disabled={searchResults.length === 0}
                title="上一个 (Shift+Enter)"
              >
                <i className="fas fa-chevron-up"></i>
              </button>
              
              <button 
                className="btn btn-sm btn-outline-secondary"
                onClick={onNext}
                disabled={searchResults.length === 0}
                title="下一个 (Enter)"
              >
                <i className="fas fa-chevron-down"></i>
              </button>
            </div>
          </div>
        )}
        
        {searchTerm && searchResults.length === 0 && (
          <div className="search-no-results">
            <small className="text-muted">未找到匹配结果</small>
          </div>
        )}
      </div>
    </div>
  );
};

export default SearchBar;